package com.mzkj.wanjulaile.mobile.api.modules.account.controller;

import com.google.common.collect.Maps;
import com.mzkj.common.data.StatusCode;
import com.mzkj.common.utils.Collections3;
import com.mzkj.common.utils.DateUtils;
import com.mzkj.common.utils.StringUtils;
import com.mzkj.wanjulaile.mobile.api.common.controller.BaseController;
import com.mzkj.wanjulaile.mobile.api.common.entity.ResultEntity;
import com.mzkj.wanjulaile.mobile.api.modules.account.entity.Account;
import com.mzkj.wanjulaile.mobile.api.modules.account.entity.Baby;
import com.mzkj.wanjulaile.mobile.api.modules.account.service.AccountService;
import com.mzkj.wanjulaile.mobile.api.modules.account.service.BabyService;
import com.mzkj.wanjulaile.mobile.api.modules.category.entity.SubCategory;
import com.mzkj.wanjulaile.mobile.api.modules.shoppingCart.entity.ShoppingCart;
import com.mzkj.wanjulaile.mobile.api.modules.shoppingCart.service.ShoppingCartService;
import com.mzkj.wanjulaile.mobile.api.modules.toy.entity.Toy;
import com.mzkj.wanjulaile.mobile.api.modules.toy.service.ToyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by meilein on 16/12/14.
 */
@RequestMapping("/auth/baby")
@Controller
public class BabyAuthController extends BaseController {
    @Autowired
    private BabyService babyService;
    @Autowired
    private ToyService toyService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private ShoppingCartService shoppingCartService;


    /**
     * 保存宝宝信息
     * @param request  accessToken
     * @param nickName 宝宝昵称
     * @param birthday 出生日期
     * @param sex    性别
     * @return
     */
    @RequestMapping(value = "saveBabyInfo",method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity<Account> saveBabyInfo(HttpServletRequest request, String nickName, String birthday, Integer sex) {
        ResultEntity<Account> result = new ResultEntity();
        String accountId=(String)request.getAttribute("accountId");
        if(StringUtils.isEmpty(nickName)){
            return new ResultEntity<>(StatusCode.SC4001);
        }
        if(sex==null){
            sex=0;
        }
        Baby baby = new Baby(accountId, nickName, birthday, sex);
        try {
            List<Baby> babies = babyService.getListByAccountId(accountId);
            if (Collections3.isEmpty(babies)) {
                Account account = new Account(baby.getAccountId());
                baby.setAccount(account);
                babyService.create(baby);
            } else {
                baby.setId(babies.get(0).getId());
                babyService.update(baby);
            }
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.setStatusCode(StatusCode.SC5000.getValue());
            result.setMsg(StatusCode.SC5000.getDesc());
        }
        return result;
    }

    /**
     * 获取会员宝宝信息
     * @param request  accessToken
     * @return
     */
    @RequestMapping(value = "getBabyInfo")
    @ResponseBody
    public ResultEntity<Baby> getBabyInfo(HttpServletRequest request) {
        ResultEntity result = new ResultEntity();
        String accountId=(String)request.getAttribute("accountId");
        Baby baby = null;
        try {
            List<Baby> babies = babyService.getListByAccountId(accountId);
            if (!Collections3.isEmpty(babies)) {
                baby = babies.get(0);
            }
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
            result.setData(baby);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.setStatusCode(StatusCode.SC5000.getValue());
            result.setMsg(StatusCode.SC5000.getDesc());
        }
        return result;
    }

    /**
     *
     * @param id  宝宝id
     * @return
     */
    @RequestMapping(value = "getBabyInfoById")
    @ResponseBody
    public ResultEntity<Baby> getBabyInfo(String id){
        ResultEntity<Baby>  result= new ResultEntity<>();
        try{
            Baby baby=babyService.get(id);
            result.setData(baby);
            if(baby == null){
                result.setStatusCode(StatusCode.SC1000.getValue());
                result.setMsg(StatusCode.SC1000.getDesc());
            }else{
                result.setStatusCode(StatusCode.SC0.getValue());
                result.setMsg(StatusCode.SC0.getDesc());
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            result.setStatusCode(StatusCode.SC5000.getValue());
            result.setMsg(StatusCode.SC5000.getDesc());
        }
        return result;
    }

    /**
     * 获取宝宝推荐玩具
     * @param request  accessToken
     * @return
     */
    @RequestMapping("/getBabyToyRecommend")
    @ResponseBody
    public ResultEntity<Map<String, Object>> getBabyToyRecommend(HttpServletRequest request) {
        ResultEntity<Map<String, Object>> result = new ResultEntity<>();
        String accountId=(String)request.getAttribute("accountId");
        Baby baby = null;
        Toy toy = new Toy();
        Map<String, Object> babyToy = new HashMap<String, Object>();
        try {
            List<Baby> babies = babyService.getListByAccountId(accountId);
            Account account = accountService.getAccount(accountId);
            int pageSize = 8;
            Map<String, String> pageMap = Maps.newHashMap();
            pageMap.put("limit", "limit 0 , " + pageSize);
            toy.setSqlMap(pageMap);
            //价格排序
            toy.setSorts("4");
            if (!Collections3.isEmpty(babies)) {
                baby = babies.get(0);
                if (StringUtils.isNotEmpty(baby.getBirthday())) {
                    setBabyAbility(baby);
                    setToySearchParams(baby, toy);
                    if (account.getVipType() == 0) {
                        getRecommendToysNormal(toy, babyToy);
                    } else {
                        getRecommendToys(toy, babyToy);
                    }
                    babyToy.put("baby", baby);
                    babyToy.put("toySearch", toy);
                }
            }else {
                //没有宝宝信息
                if (account.getVipType() == 0) {
                    getRecommendToysNormal(toy, babyToy);
                } else {
                    getRecommendToys(toy, babyToy);
                }
                babyToy.put("baby", baby);
                babyToy.put("toySearch", toy);
            }
            //购物车数量
            List<ShoppingCart> shoppingCartList = shoppingCartService.findList2ByAccountId(accountId);
            babyToy.put("cartCount",Collections3.isEmpty(shoppingCartList) ? 0 : shoppingCartList.size());
            result.setData(babyToy);
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.setStatusCode(StatusCode.SC5000.getValue());
            result.setMsg("获取宝宝推荐失败");
        }
        return result;
    }
    private void setBabyAbility(Baby baby) {
        String birthday = baby.getBirthday();
        int babyMonths = DateUtils.getBabyMonths(birthday);
        if (babyMonths == 0){
            babyMonths = 1;
        }
        String abilitiesByAge = babyService.getBabyAbilitiesByAge(babyMonths);
        baby.setBabyAbility(abilitiesByAge);
    }

    /**
     * 正序8个
     *
     * @param toy
     * @param babyToy
     */
    private void getRecommendToysNormal(Toy toy, Map<String, Object> babyToy) {
        List<Toy> homeToyList = toyService.getHomeToyList(toy);
        List<Toy> homeRecommend1 = new ArrayList<Toy>();
        List<Toy> homeRecommend2 = new ArrayList<Toy>();
        if (!Collections3.isEmpty(homeToyList)) {
            for (int i = 0; i < 4; i++) {
                Toy toy1 = homeToyList.get(i);
                setSubCategoryList(toy1);
                homeRecommend1.add(toy1);
            }
            for (int i = 4; i < 8; i++) {
                Toy toy2 = homeToyList.get(i);
                setSubCategoryList(toy2);
                homeRecommend2.add(toy2);
            }
            babyToy.put("recommendListTwo", homeRecommend2);
            babyToy.put("recommendListOne", homeRecommend1);
        }
    }

    /**
     * 随机8个玩具
     * @param toy
     * @param babyToy
     */
    private void getRecommendToys(Toy toy, Map<String, Object> babyToy) {
        int pageSize = 20;
        Map<String, String> pageMap = Maps.newHashMap();
        pageMap.put("limit", "limit 0 , " + pageSize);
        toy.setSqlMap(pageMap);
        List<Toy> homeToyList = toyService.getHomeToyList(toy);
        List<Toy> homeRecommend1 = new ArrayList<Toy>();
        List<Toy> homeRecommend2 = new ArrayList<Toy>();
        if (!Collections3.isEmpty(homeToyList) && homeToyList.size() >= 8) {
            List<Integer> random = getRandom(homeToyList.size());
            for (int i = 0; i < 4; i++) {
                Toy toy1 = homeToyList.get(random.get(i));
                setSubCategoryList(toy1);
                homeRecommend1.add(toy1);
            }
            for (int i = 4; i < 8; i++) {
                Toy toy2 = homeToyList.get(random.get(i));
                setSubCategoryList(toy2);
                homeRecommend2.add(toy2);
            }
            babyToy.put("recommendListOne", homeRecommend1);
            babyToy.put("recommendListTwo", homeRecommend2);
        }
    }

    private void setSubCategoryList(Toy toy) {
        List<SubCategory> subCategories = toy.getSubCategories();
        List<SubCategory> subList = new ArrayList<SubCategory>();
        if (!Collections3.isEmpty(subCategories)){
            for (SubCategory temp : subCategories){
                if (null !=temp.getType()){
                    subList.add(temp);
                }
            }
        }
        toy.setSubCategories(subList);
    }


    private void setToySearchParams(Baby baby, Toy toy) {
        String birthday = baby.getBirthday();
        int babyMonths = DateUtils.getBabyMonths(birthday);
        String ageStart = null;
        String ageEnd = null;
        int level;
        if (babyMonths < 6) {
            ageStart = "0";
            ageEnd = "6";
            level = 1;
        } else if (babyMonths < 12) {
            ageStart = "6";
            ageEnd = "12";
            level = 2;
        } else if (babyMonths < 24) {
            ageStart = "12";
            ageEnd = "24";
            level = 3;
        } else if (babyMonths < 36) {
            ageStart = "24";
            ageEnd = "36";
            level = 4;
        } else if (babyMonths < 48) {
            ageStart = "36";
            ageEnd = "48";
            level = 5;
        } else {
            ageStart = "48";
            level = 6;
        }
        baby.setLever(level);
        toy.setAgeStart(ageStart);
        toy.setAgeEnd(ageEnd);
        int pageSize = 20;
        Map<String, String> pageMap = Maps.newHashMap();
        pageMap.put("limit", "limit 0 , " + pageSize);
        toy.setSqlMap(pageMap);
    }

    public List<Integer> getRandom(int size) {
        Random random = new Random();
        HashSet<Integer> hs = new HashSet<Integer>();
        while (hs.size() < 8) {
            int i = random.nextInt(size);
            hs.add(i);
        }
        List<Integer> randomList = new ArrayList<Integer>();
        for (Integer it : hs) {
            randomList.add(it);
        }
        return randomList;
    }
}
